var connect=function () {
	let name = self.name;
	if (name) {
		socket=io();
		socket.emit("log",{
			name: name,
			pic: self.random
		});
		socket.on("ok",function(data) {
			fresh(data.frends);
			document.querySelector("button").addEventListener("click",function () {
				if (self.talking) {
					let msg=document.querySelector("textarea").value;
					msg=msg.split("\n").join("");
					if (msg=="" || msg==undefined) {
						console.log("发送内容不能为空！");
						return;
					}
					let cose=new Msg(self.getUser(self.name),self.talking,msg,'text');
					self.getUser(self.talking).receive(cose);

					if (self.talking == 'saloon') {
						socket.emit("saloon",{
							text: msg,
							from: name,
							time: cose.time
						})
					}
					else {
						socket.emit("sendMessage",{
							id: self.talking,
							text: msg,
							from: name,
							time: cose.time
						})
					}
					scroll(self.talking);
					document.querySelector("textarea").value="";
				}
			});
			window.addEventListener("keyup",function(event) {
				if (event.keyCode=="13") {
					if (event.target.value) {
						event.target.value.replace("\n","")
					}
					event.preventDefault();
					event.stopPropagation();
					document.querySelector("button").click();
				}
				return false;
			});
			socket.on("message",function(data) {
				let from=data.from;
				let message=data.text;
				let target=self.name;
				let time = data.time;
				let msg=new Msg(self.getUser(from),target,message,'text',time);
				let user=self.getUser(from);
				user.receive(msg);
				scroll(from);
				if (!windowState) {
					checkNotificationPermission(function(){
						let tip = new Notification(from, {
							icon: '/images/pic/' + self.getUser(from).ifm.pic + '.jpg',
							body: message
						})
					})
				}
			})
			socket.on("saloon",function(data) {
				let from=data.from;
				let message=data.text;
				let time = data.time;
				let msg=new Msg(self.getUser(from),'saloon',message,'text',time);
				self.saloon.receive(msg);
				scroll(from);
			})
			socket.on("offline",function(data) {
				let name=data.name;
				Vue.delete(self.users,name);
			})
			socket.on("file",function(data) {
				let from = data.from;
				let file = 'data:image/jpeg;base64,' + arrayBufferToBase64(data.file);
				let target = data.target || self.name;
				let time = data.time;
				let msg=new Msg(self.getUser(from),target,file, 'image',time);
				if (data.target) {
					var user=self.getUser(target);
				}
				else {
					var user=self.getUser(from);
				}
				user.receive(msg);
				scroll(from);
			})
		});
		socket.on("fresh",function(data) {
			fresh(data.frends);
		})
	}
}


var User=function(ifm) {
	this.ifm=ifm;
	this.cose=new Array();
	this.tip=0;
}

User.prototype={
	receive(msg) {
		this.cose.push(msg);
		if (self.talking!=this.ifm.name && msg.speaker.name!=self.name) {
			this.tip++;
		}
	},
	clearTip() {
		this.tip=0;
	}
}

var Saloon = function(ifm = {
	name: 'saloon',
	pic: 3
}, users = {}) {
	User.call(this, ifm);
	this.users = users;
}
Saloon.prototype = Object.create(User.prototype);
Saloon.prototype.receive = function(msg) {
	this.cose.push(msg);
	if (self.talking!=this.ifm.name && msg.speaker.name!=self.name) {
		this.tip++;
	}
}

var socket = null;
var self=new Vue({
	el: "#main",
	data: {
		ok: false,
		name: null,
		users: {},
		talking: null,
		random: null,
		keyword: null,
		saloon: null
	},
	created() {
		this.getRandom();
		this.saloon = new Saloon();
	},
	methods: {
		talkTo(name) {
			this.talking=name;
			this.getUser(name).clearTip();
			if (windowWidth < 600) {
				window.t = true;
				document.getElementsByTagName('article')[0].style.width = '100%';
				document.getElementsByTagName('section')[0].style.width = '0';
				document.getElementsByTagName('aside')[0].style.display = 'none';
				document.getElementsByClassName('top')[0].style.position = 'fixed';
			}
		},
		change() {
			connect();
			this.ok=true;
		},
		getUser(name) {
			if (name == 'saloon') {
				return this.saloon;
			}
			return this.users[name];
		},
		getRandom() {
			this.random=Math.floor(Math.random()*10);
			return this.random;
		},
		uploadFile() {
			document.getElementById("file").click();
		},
		sendFile() {
			const file = document.getElementById("file").files[0];
			socket.emit("sendFile", {
				file, id: this.talking, from: this.name
			});
			let cose=new Msg(this.getUser(this.name),this.talking,getObjectURL(file),'image');
			this.getUser(this.talking).receive(cose);
			scroll(this.talking);
		}
	}
});

var Msg=function(speaker,target,message,type='text',time) {
	this.speaker = speaker;
	this.target = target;
	this.message = message;
	this.type = type;
	if (time) {
		this.time = time;
	}
	else {
		let time_ = new Date();
		this.time = time_.getTime();
	}
	let tempTime = new Date(this.time);
	this.time_ = tempTime.getHours()+":"+tempTime.getMinutes();
}

var fresh=function(frends) {
	for (let frend of frends) {
		if (!self.users.hasOwnProperty(frend.name)) {
			var temp=new User(frend);
			Vue.set(self.users,frend.name,temp);
		}
	}
	if (frends.indexOf(self.talking)=="-1") {
		self.talking=null;
	}
}

var scroll=function(name) {
	if (name==self.talking) {
		setTimeout(function(){
			let msg=document.getElementById("msg");
			msg.scrollTop=msg.scrollHeight;
		},100);
	}
}

let randomPic=function (el) {
	if (!self.random) {
		self.random=Math.floor(Math.random()*10);
	}
	el.src='/images/pic/'+self.random+'.jpg';
}

function arrayBufferToBase64(buffer) {
         var binary = '';
         var bytes = new Uint8Array(buffer);
         var len = bytes.byteLength;
         for (var i = 0; i < len; i++) {
               binary += String.fromCharCode(bytes[i]);
         }
         return window.btoa(binary);
}


function getObjectURL(file) {
    var url = null ;

    // 下面函数执行的效果是一样的，只是需要针对不同的浏览器执行不同的 js 函数而已

    if (window.createObjectURL!=undefined) { // basic

        url = window.createObjectURL(file) ;

    } else if (window.URL!=undefined) { // mozilla(firefox)
        url = window.URL.createObjectURL(file) ;

    } else if (window.webkitURL!=undefined) { // webkit or chrome

        url = window.webkitURL.createObjectURL(file) ;

    }

    return url ;

}

function imageViewer(src, image) {
	let width = image.naturalWidth;
	let height = image.naturalHeight;
	if (width>1000) {
		let rate = 1000/width;
		width = 1000;
		height = parseInt(rate * height);
	}
	if (width>500) {
		let rate = 500/height;
		height = 500;
		width = parseInt(rate * width);
	}
	const img = new Image();
	img.src = src;
	img.style.margin = 0;
	img.style.width = width+"px";
	img.style.height = height+"px";
	img.style.position = "absolute";
	img.style.top = "50%";
	img.style.left = "50%";
	img.style.transform = "translate(-50%,-50%)";
	const newWin = window.open('', '','toolbar=no,location=no,status=no,titlebar=no,menubar=no,directories=no,resizable=no,scrollbars=yes,width='+parseInt(width+20)+",height="+parseInt(height+12));
	newWin.document.write(img.outerHTML);
	newWin.document.title="图片预览";
	newWin.document.close();
}

var windowWidth;
window.onload = function() {
	windowWidth = document.body.clientWidth;
	document.getElementById('userName').focus();
}
window.onresize = function() {
	windowWidth = document.body.clientWidth;
	if (windowWidth >= 600 && window.t) {
		slideBack();
	}
}

function slideBack() {
	document.getElementsByTagName('section')[0].style = {};
	document.getElementsByTagName('article')[0].style = {};
	document.getElementsByTagName('aside')[0].style = {};
	document.getElementsByClassName('top')[0].style = {};
	window.t = false;
}

function checkNotificationPermission(callback = function(){}) {
	if (Notification.permission != 'granted') {
		Notification.requestPermission(permission => {
			if (permission == 'granted') {
				callback();
			}
		});
	}
	else {
		callback();
	}
}

windowState = true;
document.addEventListener("visibilitychange", function() {
    console.log(document.visibilityState);
    if(document.visibilityState == "hidden") {
        windowState = false;
    } else if (document.visibilityState == "visible") {
        windowState = true;
    }
});
